from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from sqlalchemy.testing.pickleable import User

from database import get_db
from schemas.doctor_schemas import *
from services.auth_service import require_user

from config import *  # 导入所有配置
from models.user_models import *

from datetime import date
from typing import List
from fastapi import Query
from sqlalchemy.orm import Session
from sqlalchemy import or_, and_

from services.user_service import get_all_users,get_user,create_user,delete_user,update_user


from schemas.doc_schedule_schemas import ScheduleQuery, DoctorScheduleResponse  ################
from fastapi import HTTPException
from typing import List, Dict, Union


router = APIRouter()

@router.get("/doctors/departments", response_model=List[str])
def get_departments(db: Session = Depends(get_db)):
    departments = db.query(Doctor.department).distinct().all()
    # departments 是 List[Tuple[str]]，需要提取出字符串
    return [dept[0] for dept in departments if dept[0] is not None]

@router.get("/doctors")
def get_doctors(db: Session = Depends(get_db),user: User = Depends(require_user(UserType.ADMIN))):
    return get_all_users(UserType.DOCTOR,db)

# 查询单个医生的信息
@router.get("/doctors/{doctor_id}")
def get_doctor(doctor_id:int,db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN,UserType.DOCTOR,UserType.PATIENT,UserType.PHARMACIST))):
    return get_user(UserType.DOCTOR,db,doctor_id)

@router.post("/doctors")
def create_doctor(doctor:DoctorCreate,db:Session=Depends(get_db),user: User = Depends(require_user(UserType.ADMIN))):
    return create_user(UserType.DOCTOR, db, doctor)

@router.delete("/doctors/{doctor_id}")
def delete_doctor(doctor_id: int,db: Session = Depends(get_db),
                   user=Depends(require_user(UserType.ADMIN))):
    return delete_user(UserType.DOCTOR,db,doctor_id)


@router.put("/doctors/{doctor_id}")
def update_doctor(doctor_id: int, doctor_update: DoctorUpdate, db: Session = Depends(get_db),
                   user=Depends(require_user(UserType.ADMIN,UserType.DOCTOR))):
    if user["user_type"] == 'DOCTOR' and user['user_ref_id'] != doctor_id:
        raise HTTPException(
            status_code=403,
            detail=f"Doctor with ID {user['user_ref_id']} is not allowed to update patient {doctor_id}."
        )
    return update_user(UserType.DOCTOR, db, doctor_update, doctor_id)


